package com.crr.controller;

import cn.hutool.core.bean.BeanUtil;
import com.crr.bean.Employee;
import com.crr.common.bean.PageBean;
import com.crr.common.bean.ResultBean;
import com.crr.common.controller.BaseController;
import com.crr.common.group.ISave;
import com.crr.common.group.IUpdate;
import com.crr.query.EmployeeQuery;
import com.crr.service.EmployeeService;
import com.crr.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "员工管理")
@RequestMapping("/v1")
public class EmployeeController extends BaseController {

    @Autowired
    EmployeeService employeeService;

    @Autowired
    UserService userService;

    @ApiOperation("保存员工")
    @PostMapping("/employee")
    public ResultBean save(@Validated(ISave.class) @RequestBody Employee employee, BindingResult result) {
        validate(result);
        //检查用户名是否存在
        int rs = userService.queryUserByAccount(employee.getUser().getUsername());
        if (rs == 1) {
            return fail("该用户名已占用！");
        }
        rs = employeeService.save(employee);
        return saveResult(rs);
    }


    @ApiOperation("员工列表")
    @PostMapping("/employee/query")
    public ResultBean query(@RequestBody EmployeeQuery query) {
        Map map = BeanUtil.beanToMap(query);
        PageBean bean = employeeService.query(map);
        return success("员工列表", bean);
    }
    @ApiOperation("所有员工列表")
    @PostMapping("/employee/queryAll")
    public ResultBean query() {
        List<Map> list = employeeService.queryAll();
        return success("员工列表", list);
    }
    @ApiOperation("修改员工")
    @PutMapping("/employee")
    public ResultBean update(@Validated({IUpdate.class}) @RequestBody Employee employee, BindingResult result){
        validate(result);
        int res = employeeService.update(employee);
        return updateResult(res);
    }
    @ApiOperation("删除员工")
    @DeleteMapping("/employee")
    public ResultBean delete(@RequestParam(value = "id",required = true) int id){
        int res= employeeService.delete(id);
        return deleteResult(res);
    }


}
